package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;


    @Override
    public List<CategoryDTO> listCategoryByPid(Long pid) {
        //select * from tb_category where parent_id = #{pid}
        List<Category> categoryList = this.list(new QueryWrapper<Category>().eq("parent_id", pid));

        //list<Category> ==> list<CategoryDTO>
        return CategoryDTO.convertEntityList(categoryList);
    }

    @Override
    public CategoryDTO queryCategoryById(Long id) {

        return new CategoryDTO(this.getById(id));
    }

    @Override
    public List<CategoryDTO> listCategoryByIds(List<Long> ids) {

        return CategoryDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public List<CategoryDTO> listCategoryByBrand(Long bid) {
//        List<Category> categories = baseMapper.listCategoryByBid(bid);
//        return CategoryDTO.convertEntityList(categories);
        //使用mybatis-plus进行查询操作流程
        //1.先访问中间表，根据品牌id，获取分类id的集合；
        //2.再根据分类id的集合查询分类的集合
        List<Long> categoryIds = this.categoryBrandService
                .query()
                .eq("brand_id", bid)
                .list()
                .stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        //首先查询品牌id，拿到品牌id对应的集合，利用stream流将list集合中的元素放入stream中
        //接着使用map方法，将stream的Category变为long（分类id），最终使用collect放入集合中
        if(CollectionUtils.isEmpty(categoryIds)) {
            throw new LyException(204,"对应分类不存在");
        }
        return this.listCategoryByIds(categoryIds);
    }
}